package com.arunsawad.ilertu.common;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHandler extends SQLiteOpenHelper {
	// database
	private static final String DB_NAME = "ilertudb";
	private static final int DB_VERSION = 1;
	private static String DB_PATH = "";

	// table name
	private static final String TB_EMERGENCIES = "emergencies";

	public DbHandler(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
		DB_PATH = "/data/data/"
				+ context.getApplicationContext().getPackageName()
				+ "/databases/";
		try {
			this.getReadableDatabase();
		} catch (SQLiteException ex) {

		}
	}

	// create table
	@Override
	public void onCreate(SQLiteDatabase db) {
		if (!isDbExist()) {
			String query = "CREATE TABLE "
					+ TB_EMERGENCIES
					+ " (nameEn TEXT, nameTh TEXT, website TEXT, image TEXT, tel TEXT)";
			db.execSQL(query);
		}
	}

	// update database
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// Drop older table if existed
		db.execSQL("DROP TABLE IF EXISTS " + TB_EMERGENCIES);

		// Create tables again
		onCreate(db);
	}

	public boolean isDbExist() {
		SQLiteDatabase db = null;
		try {
			db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null,
					SQLiteDatabase.OPEN_READONLY);
			if (db != null) {
				Cursor cursor = db.query("sqlite_master",
						new String[] { "name" }, "type = 'table'", null, null,
						null, null);
				return cursor.getCount() > 1;
			}
		} catch (SQLiteException e) {
			return false;
		}
		return false;
	}
}